<!-- 设备工作时长报表-->

<template>
    <div class="wrapper">
        <!-- 报表标题组件-->
        <ReportTitle :titleInfo="titleInfo" @handleExport="handleExport" />
        <!-- 报表检索条件组件 -->
        <ReportSearch 
            :loading="loading"
            :searchFormDatas="searchFormDatas" 
            v-model:searchForm="searchForm"
            @handleSearchForm="handleSearchForm"
            @handleResetForm="handleResetForm" />
        <!-- 报表表格标题组件-->
        <ReportTableTitle :tableTitle="tableTitle" />
        <!-- 报表表格组件-->
        <ReportTable 
            :loading="loading" 
            :tableData="tableData" 
            :pageInfo="pageInfo"
            :summaryData="summaryData"
            :tableColumnData="tableColumnData" 
            :tableColumnWidthData="tableColumnWidthData"/>
        <!-- 报表表格分页组件-->
        <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import ReportTitle from '@/components/reportTitle/index.vue';
import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTableTitle from '@/components/reportTableTitle/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/equipOperateTime';
import * as cookies from "@/utils/cache/cookies";
import * as basicServer from '@/api/modules/common';

import { dateOptions, defaultShiftOptions } from '@/constant/selectOptions';
import { getYesterday, getCurYearMonth } from '@/utils/date';
import { apiFn, deepCopy, exportReportFile } from '@/utils/utilFns';

// 报表标题信息
const titleInfo = reactive({
    title: '设备工作时长报表',
    description: ""
});

// 报表表格标题
const defaultTitle = '设备工作时长报表';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    orgIds: local.getItem('defaultOrgIds'),
    dateType: '1',
    timeFrame: [getYesterday(), getYesterday()],
    shiftType: '-1'
};

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

// 加载状态
const loading = ref(false);

// 表头数据
const tableColumnData = ref([]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = {
    tyDate: "90",
	v_total: "90",
	lv_total: "90"
};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择所属组织',
        rules:[{required: true, message: '请选择所属组织', trigger: ['blur, change']}]
    },
    {
        id: 1,
        type: 'select',
        label: '日期类型',
        prop: 'dateType',
        options: dateOptions,
        clearable: false,
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 2,
        type: 'dateRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules:[{required: true, message: '请选择时间范围', trigger: ['change']}]
    },
    {
        id: 3,
        type: 'select',
        prop: 'shiftType',
        label: '班次类型',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    }
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

// 汇总数据
const summaryData = ref({});

onMounted(() => {
    getShiftOptions();
});

// 所属组织变化监听
watch(() => searchForm.orgIds, () => {
    searchForm.shiftType = '-1';
    getShiftOptions();
});

// 日期类型变化监听
watch(() => searchForm.dateType, (type) => {
    const dateMap = {
        '1': [getYesterday(), getYesterday()],
        '2': [getCurYearMonth(), getCurYearMonth()]
    };
    searchForm['timeFrame'] = dateMap[type];
});

// 获取班次options
const getShiftOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds }
    };
   
    apiFn(basicServer.getMineShiftList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[3]['options'] = [...defaultShiftOptions, ...data]
            } else {
                searchFormDatas.value[3]['options'] = defaultShiftOptions;
            }
        }).catch(() => {
            searchFormDatas.value[3]['options'] = defaultShiftOptions;
        });
};

// 获取查询参数
const getParams = () => {
    const { orgIds, dateType, timeFrame, shiftType } = searchForm;
    const { pageSize, currentPage } = pageInfo;

    const params = {
        equal: {
            orgId: orgIds,
            dateType,
            startDate: timeFrame[0].replaceAll("-", ""),
            endDate: timeFrame[1].replaceAll("-", ""),
            shiftType
        },
        limit: pageSize,
        page: currentPage,
    };

    return params;
};

// 获取报表表头
const getTableColumn = () => {
    const params = getParams();
    apiFn(server.getEquipWorkHourTableColumn, params)
        .then(res => {
            const { code, data = [], resultMsg = '' } = res;
            if (code === '200') {
                tableColumnData.value = data;
                tableTitle.value = resultMsg;
                getTableList();
            } else {
                tableColumnData.value = [];
                tableTitle.value = defaultTitle;
            }
        }).catch(() => {
            tableColumnData.value = [];
            tableTitle.value = defaultTitle;
        })
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getEquipWorkHourTableList, params)
        .then(res => {
            const { code, data, recordsTotal } = res;
            if (code === '200') {
                tableData.value = data;
                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if(loading.value) return;
    
    if(type === 'search'){
        Object.keys(defaultPageInfo).forEach(key => {
            if(key in pageInfo){
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    getTableColumn();
};

// 导出
const handleExport = () => {
    if(!tableData.value.length) {
    ElMessage.warning('无查询数据导出!'); 
    return;
}
    
    const url = window.config.APP_BASE_URL + "report/exportDispatchVehicle";
    const params = getParams();

    exportReportFile (url, "POST", {
        ElMessage: ElMessage,
		token: cookies.getToken(),
		params: params,
	});
};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });
    
    Object.keys(defaultPageInfo).forEach(key => {
        if(key in pageInfo){
            pageInfo[key] = defaultPageInfo[key];
        }
    });

    tableTitle.value = defaultTitle;
    tableColumnData.value = [];
    tableData.value = [];
};
</script>

<style lang="scss" scoped></style>